/*******************************************
 *                                         *
 *******************************************/

#include "GraphicsDevice.h"

namespace DirectXFramework
{
	namespace Graphics
	{
		GraphicsDevice::GraphicsDevice (void)
		{
			this->d3d = NULL;
			this->d3ddev = NULL;
		}

		GraphicsDevice::GraphicsDevice (Window & GameWindow)
		{
			this->d3d = NULL;
			this->d3ddev = NULL;
			this->Init(GameWindow);
		}

		GraphicsDevice::~GraphicsDevice (void)
		{
			this->CleanD3D();
		}

		BOOL GraphicsDevice::Init (Window & GameWindow)
		{
			this->ClearColor = COLOR(0, 0, 0);
			return this->InitD3D(GameWindow);
		}

		void GraphicsDevice::BeginRendering (void)
		{
			this->Clear();
			this->d3ddev->BeginScene();
		}

		void GraphicsDevice::EndRendering (void)
		{
			this->d3ddev->EndScene();
			this->d3ddev->Present(NULL, NULL, NULL, NULL);
		}

		void GraphicsDevice::Clear (void)
		{
			this->d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, ClearColor, 1.0f, 0);
			this->d3ddev->Clear(0, NULL, D3DCLEAR_ZBUFFER, ClearColor, 1.0f, 0);
		}

		void GraphicsDevice::SetClearColor (int Red, int Green, int Blue, int Alpha)
		{
			this->ClearColor = D3DCOLOR_RGBA(Red, Green, Blue, Alpha);
		}


		LPDIRECT3DDEVICE9 GraphicsDevice::GetDrawDevice (void)
		{
			return this->d3ddev;
		}

		LPDIRECT3D9 GraphicsDevice::GetDirectXDevice (void)
		{
			return this->d3d;
		}

		BOOL GraphicsDevice::InitD3D (Window & GameWindow)
		{
			BOOL Success = TRUE;

			//DirectX Initialization
			this->d3d = Direct3DCreate9(D3D_SDK_VERSION);
			
			D3DPRESENT_PARAMETERS d3dpp;
			ZeroMemory(&d3dpp, sizeof(d3dpp));
			d3dpp.Windowed = !GameWindow.GetFullScreen();
			d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
			d3dpp.hDeviceWindow = GameWindow.GetWindowHandle();
			d3dpp.EnableAutoDepthStencil = TRUE;
			d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
			d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
			d3dpp.BackBufferWidth = GameWindow.GetScreenWidth();
			d3dpp.BackBufferHeight = GameWindow.GetScreenHeight();

			this->d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, GameWindow.GetWindowHandle(),
									D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &this->d3ddev);

			if (!this->d3ddev)
				Success = FALSE;
			else
			{	
				this->d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
				this->d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
			}

			return Success;
		}

		void GraphicsDevice::CleanD3D (void)
		{
			if (this->d3ddev)
				this->d3ddev->Release();
			if (this->d3d)
				this->d3d->Release();
		}
	};
};